#include <iostream>
#include <cstring>
#include "Log.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

using namespace LogModule;
int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        std::cerr<<"Usage: "<<argv[0]<<" serve_ip serveport"<<std::endl;
        return 1;
    }
    std::string ip=argv[1];
    uint16_t port=std::stoi(argv[2]);

    //创建socketfd
    int _socketfd=socket(AF_INET,SOCK_DGRAM,0);
    if(_socketfd<0)
    {
        LOG(FATAL)<<"soketfd create error";
        return 2;
    }
    struct sockaddr_in client;
    memset(&client,0,sizeof(client));

    client.sin_port=htons(port);
    client.sin_addr.s_addr=inet_addr(ip.c_str());
    client.sin_family=AF_INET;

    while(true)
    {
        //发送消息
        std::string input;        
        std::cout<<"please enter#";
        std::getline(std::cin,input);
        //应该跳过开始和末尾的空格部分，现在的程序跳不过空格，一出现空格就返回None了
        while(!input.empty()&&input.front()==' ')input.erase(input.begin());
        while(!input.empty()&&input.back()==' ')input.erase(input.end()-1);
        int n=sendto(_socketfd,input.c_str(),input.size(),0,(struct sockaddr*)&client,sizeof(client));
        if(n<0)
        {
            LOG(FATAL)<<"send error";
        }
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len=sizeof peer;
        //如果UDPClient和UDPServe传入的ip地址不一样，程序会阻塞在此
        int m=recvfrom(_socketfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(m>0)
        {
            buffer[m]=0;
            std::cout<<buffer<<std::endl;
        }
    }
    return 0;
}